﻿using rmTest.Common;
using rmTest.Common.ConstUtil;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SSQ
{
    public partial class ssqForm : Form
    {
        public ssqForm()
        {
            InitializeComponent();
        }

        #region Data
        /// <summary>
        /// 红球集合
        /// </summary>
        private string[] RedNums =
        {
            "01","02","03","04","05","06","07","08","09","10",
            "11","12","13","14","15","16","17","18","19","20",
            "21","22","23","24","25","26","27","28","29","30",
            "31","32","33"
        };

        /// <summary>
        /// 蓝球集合
        /// </summary>
        private string[] BlueNums =
        {
            "01","02","03","04","05","06","07","08","09","10",
            "11","12","13","14","15","16"
        };

        private static readonly object frmSSQ_Lock = new object();
        private bool IsGoOn = true;

        private List<Task> taskList = new List<Task>();
        #endregion
        #region UI

        /// <summary>
        /// 点击开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Text = "Starting";
            this.btnStart.Enabled = false;
            this.IsGoOn = true;

            try
            {

                var gboControls = this.gboSSQ.Controls;
                foreach (var gboControl in gboControls)
                {
                    if (gboControl is Label)
                    {
                        Label label = gboControl as Label;
                        if (label != null)
                        {
                            label.Text = "00";
                        }
                    }
                }

                TaskFactory taskFactory = new TaskFactory();
                foreach (var gboControl in gboControls)
                {
                    if (gboControl is Label)
                    {
                        Label label = gboControl as Label;
                        if (label.Name.Contains("Blue"))//篮球刷新
                        {
                            //如果是篮球，启动一个子线程，获取一个随机数作为篮球的显示值
                            Task task = taskFactory.StartNew(() =>
                            {
                                //通过全局变量，让线程跑循环任务，只有全局变量改变后，线程才会完成
                                while (this.IsGoOn)
                                {
                                    int idx = RandomUtil.GetRandomNumberLong(0, BlueNums.Length);
                                    string sText = BlueNums[idx];
                                    UpdateLabelText(label, sText);
                                }
                            });
                            taskList.Add(task);
                        }
                        else
                        {
                            //如果是红球，启动一个子线程，获取一个随机数作为篮球的显示值
                            Task task = taskFactory.StartNew(() =>
                            {
                                //通过全局变量，让线程跑循环任务，只有全局变量改变后，线程才会完成
                                while (this.IsGoOn)
                                {
                                    int idx = RandomUtil.GetRandomNumberLong(0, RedNums.Length);
                                    string sText = RedNums[idx];
                                    //当所有红球都已获取值需要判断是否存在时，加上锁，让只有一个线程能够去判断
                                    lock (frmSSQ_Lock)
                                    {
                                        //更新红球以前，先判断获取的数字是否已存在与红球中
                                        if (!this.IsExsitRed(sText))
                                        {
                                            this.UpdateLabelText(label, sText);
                                        }
                                    }
                                }
                            });
                            taskList.Add(task);
                        }
                    }
                }

                //当前球都已变动后，可以点击Stop按钮
                taskFactory.StartNew(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(1000);
                        if (!this.IsExsitRed("00") && !this.lblBlue.Text.Equals("00"))
                        {
                            this.Invoke(new Action(() =>
                            {
                                this.btnStop.Enabled = true;
                            }));
                            break;
                        }
                    }
                });

                //当前所有线程已经完成后，label将不再变化，显示结果
                taskFactory.ContinueWhenAll(this.taskList.ToArray(), tArray => this.ShowResult());

            }
            catch (Exception ex)
            {
                Console.WriteLine("双色球启动发生异常！错误：" + ex.Message);
            }
        }

        private bool IsExsitRed(string sNumber)
        {
            foreach (var control in this.gboSSQ.Controls)
            {
                if (control is Label)
                {
                    Label lbl = (Label)control;
                    if (lbl.Name.Contains("Red") && lbl.Text.Equals(sNumber))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void UpdateLabelText(Label label, string sBlueText)
        {
            //判断是否是创建控件的线程在尝试修改线程
            if (label.InvokeRequired)
            {
                //交给UI线程去更新界面上label
                this.Invoke(new Action(() =>
                {
                    if (IsGoOn)//不延迟，点了停止，就不会再更新,放弃了最后那次更新
                    {
                        label.Text = sBlueText;
                        Console.WriteLine($"当前 UpdateLabelText 线程id：{Thread.CurrentThread.ManagedThreadId}");
                    }
                }));
            }
            else
            {
                label.Text = sBlueText;
            }
        }
        #endregion

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = true;
            this.btnStart.Text = "Start";
            this.btnStop.Enabled = false;
            this.IsGoOn = false;
            //此处不能直接显示所有球的Text，修改球的Text的数据的线程必须自己停止，所有线程停止后才可以显示结果
        }

        /// <summary>
        /// 弹框提示数据
        /// </summary>
        private void ShowResult()
        {
            MessageBox.Show(string.Format("本期双色球结果为红球：{0} {1} {2} {3} {4} {5}  蓝球：{6}"
                , this.lblRed1.Text
                , this.lblRed2.Text
                , this.lblRed3.Text
                , this.lblRed4.Text
                , this.lblRed5.Text
                , this.lblRed6.Text
                , this.lblBlue.Text));
        }
    }
}
